package com.ly.blog2zuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * token 认证
 * @author: lyMaster
 * @time: 2020/7/19 21:26
 */
@Component
public class MyZuulFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre"; //定义 filter类型 pre：之前 route：进入微服务 post：完成后 error 错误
    }

    @Override
    public int filterOrder() {
        return 0; //定义顺序 越小优先级越高
    }

    @Override
    public boolean shouldFilter() {
        return true; //是否执行
    }

    @Override
    public Object run() throws ZuulException { //执行的操作
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getParameter("token");

        if(token == null){
//            context.setSendZuulResponse(false);
//            context.setResponseStatusCode(401);
//            try {
//                context.getResponse().getWriter().write("no token!!");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }

        return null;
    }
}
